<?php
/**
 * Import Multiple Images during Product Import
 * Copyright ? 2011 Web Design by Capacity Web Solutions Pvt. Ltd. All Rights Reserved.
 * http://www.capacitywebsolutions.com
 */

class CapacityWebSolutions_ImportProduct_Model_Convert_Adapter_Product extends Mage_Catalog_Model_Convert_Adapter_Product
{
    /**
     * Save product (import)
     *
     * @param array $importData
     * @throws Mage_Core_Exception 
     * @return bool
     */
    protected $custom_options = array();


    public function saveRow(array $importData)
    {
        $product = $this->getProductModel()
            ->reset();

        if(isset($importData['CategoryOption'])){
            $this->_categoryOption($importData);
            return true;
        }

        if(isset($importData['position']) && isset($importData['category id']) && isset($importData['sku'])){
            return $this->_importAssociationCategory($importData);
        }

        if(isset($importData['associationCategory'])){

            return $this->_associationCategory($importData);
        } 
        if(isset($importData['Secondary categories']) && !isset($importData['Category'])){
            $productId = $product->getIdBySku($importData['Product code']);
            if ($productId) {
                $product->load($productId);
            }
            if(!$product->getId()){
                $message = Mage::helper('catalog')->__('Skip import row, sku "%s" cannot find product', $importData['Product code']);
                Mage::throwException($message); 
            }
            $condition = array();
            $cCategoryA = explode(';',$importData['Secondary categories']);
            foreach($cCategoryA as $Category){

                $CategoryA = explode('>',$Category);
                // $cname[] = $CategoryA[count($CategoryA)-1]; 
                if($CategoryA[count($CategoryA)-1]) $condition[] = array('eq'=>$CategoryA[count($CategoryA)-1]);

            }
            if(count($condition)>0){
                $collection = Mage::getModel('catalog/category')->getCollection(); 
                $collection->addFieldToFilter('name',$condition);
                // $collection->getSelect()->where("name in (`".implode(',',$cname).")");
                //echo  $collection->getSelect();
                // Mage::log($collection->getColumnValues('entity_id'));
                $category_ids = $collection->getColumnValues('entity_id'); 
            }
            if (isset($category_ids)) {
                $ids = $product->getCategoryIds();
                $category_ids = implode(',',array_merge($ids,$category_ids));
                $product->setCategoryIds($category_ids);
                $product->save(); 
            }else{
                $message = Mage::helper('catalog')->__('Skip import row, sku "%s" cannot find category', $importData['Product code']);
                Mage::throwException($message); 
            }   
            return true; 

        }
        if(isset($importData['Category'])){

            $oneCategoryA = explode('>',$importData['Category']);
            $condition = array();
            if($oneCategoryA[count($oneCategoryA)-1]) $condition[] = array('eq'=>$oneCategoryA[count($oneCategoryA)-1]);
            $cCategoryA = explode(';',$importData['Secondary categories']);
            foreach($cCategoryA as $Category){

                $CategoryA = explode('>',$Category);
                // $cname[] = $CategoryA[count($CategoryA)-1]; 
                if($CategoryA[count($CategoryA)-1]) $condition[] = array('eq'=>$CategoryA[count($CategoryA)-1]);

            }

            if(count($condition)>0){
                $collection = Mage::getModel('catalog/category')->getCollection(); 
                $collection->addFieldToFilter('name',$condition);
                // $collection->getSelect()->where("name in (`".implode(',',$cname).")");
                //echo  $collection->getSelect();
                // Mage::log($collection->getColumnValues('entity_id'));
                $importData['category_ids'] = implode(',',$collection->getColumnValues('entity_id')); 
            }
            if(empty($importData['category_ids'])){
                $importData['category_ids'] = '370';
                // $message = Mage::helper('catalog')->__('Skip import row, sku "%s" cannot find category', $importData['Product code']);
                // Mage::throwException($message); 
            }
            unset($importData['Category']);
            unset($importData['Secondary categories']);  
            $importData['sku2'] = $importData['sku']=$importData['Product code'];
            unset($importData['Product code']);
            $importData['status']='Enabled';
            unset($importData['Available']);
            $importData['name']=$importData['Product name'];
            unset($importData['Product name']);
            $importData['url_key']=$importData['SEO name'];
            unset($importData['SEO name']);
            $importData['description']=$importData['Description'];
            unset($importData['Description']);
            $importData['short_description']=$importData['Short description'];
            unset($importData['Short description']); 
            $importData['meta_title']=$importData['Page title'];
            unset($importData['Page title']); 
            $importData['meta_keyword']=$importData['Meta keywords'];
            unset($importData['Meta keywords']);
            $importData['meta_description']=$importData['Meta description'];
            unset($importData['Meta description']);
            $importData['price']=$importData['Price'];
            unset($importData['Price']);
            $importData['weight']=$importData['Weight'];
            unset($importData['Weight']);
            $importData['qty']= '999';
            $importData['use_config_min_sale_qty']=1;
            $importData['is_in_stock']='1';
            $importData['store']='admin';
            $importData['websites']='base';
            $importData['attribute_set']='Default';
            $importData['type']='simple';
            $importData['store_id']='0';
            $importData['product_type_id']='simple';
            $importData['use_config_manage_stock']='1';
            $importData['tax_class_id']='None';
            $importData['visibility']='Catalog, Search';


            //exit; 
        }
        if(isset($importData['Lower limit']) && intval($importData['Lower limit'])>0 ){
            $productId = $product->getIdBySku($importData['Product code']);
            if ($productId) {
                $product->load($productId);
            }
            if(!$product->getId()){
                $message = Mage::helper('catalog')->__('Skip import row, sku "%s" cannot find product', $importData['Product code']);
                Mage::throwException($message); 
            }
            $MembershipIds = array('Platinium'=>5,'28'=>'5','Gold'=>'4','30'=>'4','Silver'=>'3','29'=>'3','Bronze'=>'2','32'=>'2');
            $MembershipId  = array_key_exists(trim($importData['Membership']),$MembershipIds) ? $MembershipIds[trim($importData['Membership'])]:'32000';
            $importData['tier_prices'] =  intval($importData['Lower limit']).'='.$importData['Price'].'='.$MembershipId;
            unset($importData['Product code']); unset($importData['Price']); unset($importData['Membership']);unset($importData['Lower limit']); 
            $this->_editTierPrices($product, $importData['tier_prices']); 
            $product->save();
            return true;
        }
        if(isset($importData['weight2'])){
            $importData['sku'] =   $importData['product_id'];
            $importData['digg'] =   $importData['diggs_total'];
            $importData['shelf_no'] =   $importData['product_shelf'];
            $importData['ref_cost'] =   $importData['cost_price'];
            $importData['created_date'] =   date('Y-m-d',$importData['timestamp']);
            unset($importData['product_id']); unset($importData['cost_price']); unset($importData['diggs_total']);unset($importData['product_shelf']);
            unset($importData['timestamp']);
        }
        if(isset($importData['Detailed image'])){
            $importData['sku'] =   $importData['Product code'];
            if(stripos($importData['Detailed image'],'#')===false){
                $image_file = basename($importData['Detailed image']);
            }else{
                $image_file = basename(substr($importData['Detailed image'],0,stripos($importData['Detailed image'],'#')));
            }
            $image_file = DS.$image_file;
            $file = Mage::getBaseDir('media') . DS . 'import' . trim($image_file); 
            unset($importData['Product code']);unset($importData['Detailed image']);
            $product = Mage::getModel ( 'catalog/product' );
            $product_id = $product->getIdBySku ( $importData['sku'] );
            if( !$product_id ){
                $message = Mage::helper('catalog')->__('Skip import row,  "%s" not exists', $importData['sku']);
                Mage::throwException($message);  
                return true;
            }
            $product->load ( $product_id );
            /**
             * BEGIN REMOVE EXISTING MEDIA GALLERY
             */
            $attributes = $product->getTypeInstance ()->getSetAttributes ();
            if (isset ( $attributes ['media_gallery'] )) {
                $gallery = $attributes ['media_gallery'];
                $file = realpath($file);
                if (!$file || !file_exists($file)) {
                    Mage::throwException(Mage::helper('catalog')->__('Image does not exist.'));
                }
                $pathinfo = pathinfo($file);
                $imgExtensions = array('jpg','jpeg','gif','png');
                if (!isset($pathinfo['extension']) || !in_array(strtolower($pathinfo['extension']), $imgExtensions)) {
                    Mage::throwException(Mage::helper('catalog')->__('Invalid image file type.'));
                }

                $fileName       = Mage_Core_Model_File_Uploader::getCorrectFileName($pathinfo['basename']);
                $dispretionPath = Mage_Core_Model_File_Uploader::getDispretionPath($fileName);
                $fileName       = $dispretionPath . DS . $fileName;
                $fileName = str_replace(DS, '/', $fileName);
                //Get the images
                if ($gallery->getBackend ()->getImage ( $product, $fileName)) {
                    $message = Mage::helper('catalog')->__('Skip import row,  "%s" has exists', $image_file);
                    Mage::throwException($message); 
                    return true;

                }
            }
            if($importData['Pair type']=='M') {
                $importData['image'] =  $importData['small_image'] = $importData['thumbnail'] = $image_file;
                $importData['image_label'] =  $importData['small_image_label'] = $importData['thumbnail_label'] = $product->getName(); 
                unset($importData['Pair type']); unset($importData['Product code']); unset($importData['Thumbnail']);unset($importData['Detailed image']);

            }else{
                $gallery->getBackend()->addImage($product, Mage::getBaseDir('media') . DS . 'import' . trim($image_file), null, false, false);
                $product->save ();
                return true ; 
            }





        }
        if(isset($importData['deleteimages'])){
            $collection = Mage::getResourceModel('catalog/product_collection');
            $collection->addAttributeToSelect(Mage::getSingleton('catalog/config')->getProductAttributes());
            foreach($collection as $product){
                $attributes = $product->getTypeInstance(true)->getSetAttributes($product);
                if (!isset($attributes['media_gallery'])) {
                    continue; 
                }
                $mediaGalleryAttribute = $attributes['media_gallery'];
                /* @var $mediaGalleryAttribute Mage_Catalog_Model_Resource_Eav_Attribute */
                $mediaBackend = $mediaGalleryAttribute->getBackend();
                $attrCode = $mediaBackend->getAttribute()->getAttributeCode();
                $product = Mage::getModel('catalog/product')->load($product->getId()); 
                $mediaGalleryData = $product->getData($attrCode);
                if (!isset($mediaGalleryData['images']) || !is_array($mediaGalleryData['images'])) {

                    continue; 
                }
                foreach ($mediaGalleryData['images'] as &$image) {
                    $image['removed'] = 1;
                }
                $product->setData($attrCode, $mediaGalleryData);
                $product->save();
            }
            return true;
        }
        //Mage::log($image_file);
        //Mage::log($importData['tier_prices']);
        //Mage::log($importData); 
        if (empty($importData['store'])) {
            if (!is_null($this->getBatchParams('store'))) {
                $store = $this->getStoreById($this->getBatchParams('store'));
            } else {
                $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'store');
                Mage::throwException($message);
            }
        }
        else {
            $store = $this->getStoreByCode($importData['store']);
        }

        if ($store === false) {
            $message = Mage::helper('catalog')->__('Skip import row, store "%s" field not exists', $importData['store']);
            Mage::throwException($message);
        }

        if (empty($importData['sku'])) {
            $message = Mage::helper('catalog')->__('Skip import row, required field "%s" not defined', 'sku');
            Mage::throwException($message);
        }
        $product->setStoreId($store->getId());
        $productId = $product->getIdBySku($importData['sku']);

        if ($productId) {
            $product->load($productId);
        }
        else {
            $productTypes = $this->getProductTypes();
            $productAttributeSets = $this->getProductAttributeSets();

            /**
             * Check product define type
             */
            if (empty($importData['type']) || !isset($productTypes[strtolower($importData['type'])])) {
                $value = isset($importData['type']) ? $importData['type'] : '';
                $message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'type');
                Mage::throwException($message);
            }
            $product->setTypeId($productTypes[strtolower($importData['type'])]);
            /**
             * Check product define attribute set
             */
            if (empty($importData['attribute_set']) || !isset($productAttributeSets[$importData['attribute_set']])) {
                /*$value = isset($importData['attribute_set']) ? $importData['attribute_set'] : '';
                $message = Mage::helper('catalog')->__('Skip import row, is not valid value "%s" for field "%s"', $value, 'attribute_set');
                Mage::throwException($message);*/
            }
            $product->setAttributeSetId($productAttributeSets[$importData['attribute_set']]);
            foreach ($this->_requiredFields as $field) {
                $attribute = $this->getAttribute($field);
                if (!isset($importData[$field]) && $attribute && $attribute->getIsRequired()) {
                    $message = Mage::helper('catalog')->__('Skip import row, required field "%s" for new products not defined', $field);
                    Mage::throwException($message);
                }
            }
        }

        $this->setProductTypeInstance($product);

        if (isset($importData['category_ids'])) {
            $product->setCategoryIds($importData['category_ids']);
        }

        if(
            isset($importData['tier_prices'])
            && !empty($importData['tier_prices'])
        ){
            $this->_editTierPrices($product, $importData['tier_prices']);
        }

        /*	if category name is in csv file		*/
        if (isset($importData['categories'])) {

            $categoryIds = $this->_addCategories($importData['categories'], $store);
            if ($categoryIds) {
                $product->setCategoryIds($categoryIds);
            }
        }
        foreach ($this->_ignoreFields as $field) {
            if (isset($importData[$field])) {
                unset($importData[$field]);
            }
        }

        if ($store->getId() != 0) {
            $websiteIds = $product->getWebsiteIds();
            if (!is_array($websiteIds)) {
                $websiteIds = array();
            }
            if (!in_array($store->getWebsiteId(), $websiteIds)) {
                $websiteIds[] = $store->getWebsiteId();
            }
            $product->setWebsiteIds($websiteIds);
        }

        if (isset($importData['websites'])) {
            $websiteIds = $product->getWebsiteIds();
            if (!is_array($websiteIds)) {
                $websiteIds = array();
            }
            $websiteCodes = explode(',', $importData['websites']);
            foreach ($websiteCodes as $websiteCode) {
                try {
                    $website = Mage::app()->getWebsite(trim($websiteCode));
                    if (!in_array($website->getId(), $websiteIds)) {
                        $websiteIds[] = $website->getId();
                    }
                }
                catch (Exception $e) {}
            }
            $product->setWebsiteIds($websiteIds);
            unset($websiteIds);
        }

        foreach ($importData as $field => $value) {
            if (in_array($field, $this->_inventoryFields)) {
                continue;
            }
            if (in_array($field, $this->_imageFields)) {
                continue;
            }
            if (is_null($value)) {
                continue;
            }
            $attribute = $this->getAttribute($field);
            if (!$attribute) {

                if(strpos($field,':')!==FALSE && strlen($value)) {
                    $values=explode('|',$value);
                    if(count($values)>0) {
                        @list($title,$type,$is_required,$sort_order) = explode(':',$field);
                        $title = ucfirst(str_replace('_',' ',$title));
                        $custom_options[] = array(
                            'is_delete'=>0,
                            'title'=>$title,
                            'previous_group'=>'',
                            'previous_type'=>'',
                            'type'=>$type,
                            'is_require'=>$is_required,
                            'sort_order'=>$sort_order,
                            'values'=>array()
                        );
                        foreach($values as $v) {
                            $parts = explode(':',$v);
                            $title = $parts[0];
                            if(count($parts)>1) {
                                $price_type = $parts[1];
                            } else {
                                $price_type = 'fixed';
                            }
                            if(count($parts)>2) {
                                $price = $parts[2];
                            } else {
                                $price =0;
                            }
                            if(count($parts)>3) {
                                $sku = $parts[3];
                            } else {
                                $sku='';
                            }
                            if(count($parts)>4) {
                                $sort_order = $parts[4];
                            } else {
                                $sort_order = 0;
                            }
                            switch($type) {
                            case 'file':
                                break;

                            case 'field':
                                case 'area':
                                    $custom_options[count($custom_options) - 1]['max_characters'] = $sort_order;


                                case 'date':
                                    case 'date_time':
                                        case 'time':
                                            $custom_options[count($custom_options) - 1]['price_type'] = $price_type;
                                            $custom_options[count($custom_options) - 1]['price'] = $price;
                                            $custom_options[count($custom_options) - 1]['sku'] = $sku;
                                            break;

                                        case 'drop_down':
                                            case 'radio':
                                                case 'checkbox':
                                                    case 'multiple':
                                                        default:
                                                            $custom_options[count($custom_options) - 1]['values'][]=array(
                                                                'is_delete'=>0,
                                                                'title'=>$title,
                                                                'option_type_id'=>-1,
                                                                'price_type'=>$price_type,
                                                                'price'=>$price,
                                                                'sku'=>$sku,
                                                                'sort_order'=>$sort_order,
                                                            );
                                                            break;
                            }
                        }
                    }
                }

                continue;
            }

            $isArray = false;
            $setValue = $value;

            if ($attribute->getFrontendInput() == 'multiselect') {
                $value = explode(self::MULTI_DELIMITER, $value);
                $isArray = true;
                $setValue = array();
            }

            if ($value && $attribute->getBackendType() == 'decimal') {
                $setValue = $this->getNumber($value);
            }


            if ($attribute->usesSource()) {
                $options = $attribute->getSource()->getAllOptions(false);

                if ($isArray) {
                    foreach ($options as $item) {
                        if (in_array($item['label'], $value)) {
                            $setValue[] = $item['value'];
                        }
                    }
                }
                else {
                    $setValue = false;
                    foreach ($options as $item) {
                        if ($item['label'] == $value) {
                            $setValue = $item['value'];
                        }
                    }
                }
            }

            $product->setData($field, $setValue);
        }

        if (!$product->getVisibility()) {
            $product->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE);
        }

        $stockData = array();
        $inventoryFields = isset($this->_inventoryFieldsProductTypes[$product->getTypeId()])
            ? $this->_inventoryFieldsProductTypes[$product->getTypeId()]
            : array();
        foreach ($inventoryFields as $field) {
            if (isset($importData[$field])) {
                if (in_array($field, $this->_toNumber)) {
                    $stockData[$field] = $this->getNumber($importData[$field]);
                }
                else {
                    $stockData[$field] = $importData[$field];
                }
            }
        }
        $product->setStockData($stockData);

        $imageData = array();
        foreach ($this->_imageFields as $field) {
            if (!empty($importData[$field]) && $importData[$field] != 'no_selection') {
                if (!isset($imageData[$importData[$field]])) {
                    $imageData[$importData[$field]] = array();
                }
                $imageData[$importData[$field]][] = $field;
            }
        }

        if(Mage::getVersion() < "1.5.0.0"){
            foreach ($imageData as $file => $fields) {
                try {
                    $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . $file, $fields);
                }
                catch (Exception $e) {}
            }
        }
        else
        {
         /*	
          Code for image upload in version 1.5.x.x and above
          */		
            $mediaGalleryBackendModel = $this->getAttribute('media_gallery')->getBackend();

            $arrayToMassAdd = array();

            foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
                if (isset($importData[$mediaAttributeCode])) {
                    $file = $importData[$mediaAttributeCode];
                    if (trim($file) && !$mediaGalleryBackendModel->getImage($product, $file)) {
                        $arrayToMassAdd[] = array('file' => trim($file), 'mediaAttribute' => $mediaAttributeCode);
                    }
                }
            }

            $addedFilesCorrespondence =
                $mediaGalleryBackendModel->addImagesWithDifferentMediaAttributes($product, $arrayToMassAdd, Mage::getBaseDir('media') . DS . 'import', false, false);

            foreach ($product->getMediaAttributes() as $mediaAttributeCode => $mediaAttribute) {
                $addedFile = '';
                if (isset($importData[$mediaAttributeCode . '_label'])) {
                    $fileLabel = trim($importData[$mediaAttributeCode . '_label']);
                    if (isset($importData[$mediaAttributeCode])) {
                        $keyInAddedFile = array_search($importData[$mediaAttributeCode],
                            $addedFilesCorrespondence['alreadyAddedFiles']);
                        if ($keyInAddedFile !== false) {
                            $addedFile = $addedFilesCorrespondence['alreadyAddedFilesNames'][$keyInAddedFile];
                        }
                    }

                    if (!$addedFile) {
                        $addedFile = $product->getData($mediaAttributeCode);
                    }
                    if ($fileLabel && $addedFile) {
                        $mediaGalleryBackendModel->updateImage($product, $addedFile, array('label' => $fileLabel));
                    }
                }
            }


        }

        /**
         * Allows you to import multiple images for each product.
         * Simply add a 'gallery' column to the import file, and separate
         * each image with a semi-colon.
         */
        try {
            if(isset($importData["gallery"])){
                $galleryData = explode(';',$importData["gallery"]);
                //Mage::log($galleryData);
                foreach($galleryData as $gallery_img)
                    /**
                     * @param directory where import image resides
                     * @param leave 'null' so that it isn't imported as thumbnail, base, or small
                     * @param false = the image is copied, not moved from the import directory to it's new location
                     * @param false = not excluded from the front end gallery
                     */
                {
                    $product->addImageToMediaGallery(Mage::getBaseDir('media') . DS . 'import' . trim($gallery_img), null, false, false);
                }
            }
        }
        catch (Exception $e) {}        
            /* End Modification */

            $product->setIsMassupdate(true);
        $product->setExcludeUrlRewrite(true);

        $product->save();
        /* Add the custom options specified in the CSV import file 	*/
        if(isset($custom_options)){
            if(count($custom_options)) {
                foreach($custom_options as $option) {
                    try {
                        $opt = Mage::getModel('catalog/product_option');
                        $opt->setProduct($product);
                        $opt->addOption($option);
                        $opt->saveOptions();
                    }
                    catch (Exception $e) {}
                }
            }
        }
        return true;
    }

    protected $_categoryCache = array();
    /*	Add category and sub category.	 */
    protected function _addCategories($categories, $store)
    {

        $rootId = $store->getRootCategoryId();

        if (!$rootId) {
            /* If stoder not create that mense admin then assign 1 to storeId */
            $storeId = 1;
            $rootId = Mage::app()->getStore($storeId)->getRootCategoryId();

        }

        if($categories=="")
            return array();
        $rootPath = '1/'.$rootId;
        if (empty($this->_categoryCache[$store->getId()])) {
            $collection = Mage::getModel('catalog/category')->getCollection()
                ->setStore($store)
                ->addAttributeToSelect('name');
            $collection->getSelect()->where("path like '".$rootPath."/%'");

            foreach ($collection as $cat) {
                $pathArr = explode('/', $cat->getPath());
                $namePath = '';
                for ($i=2, $l=sizeof($pathArr); $i<$l; $i++) {
                    $name = $collection->getItemById($pathArr[$i])->getName();
                    $namePath .= (empty($namePath) ? '' : '/').trim($name);
                }
                $cat->setNamePath($namePath);
            }

            $cache = array();
            foreach ($collection as $cat) {
                $cache[strtolower($cat->getNamePath())] = $cat;
                $cat->unsNamePath();
            }
            $this->_categoryCache[$store->getId()] = $cache;
        }
        $cache =& $this->_categoryCache[$store->getId()];

        $catIds = array();
        foreach (explode(',', $categories) as $categoryPathStr) {
            $categoryPathStr = preg_replace('#\s*/\s*#', '/', trim($categoryPathStr));
            if (!empty($cache[$categoryPathStr])) {
                $catIds[] = $cache[$categoryPathStr]->getId();
                continue;
            }
            $path = $rootPath;
            $namePath = '';
            foreach (explode('/', $categoryPathStr) as $catName) {
                $namePath .= (empty($namePath) ? '' : '/').strtolower($catName);
                if (empty($cache[$namePath])) {
                    $cat = Mage::getModel('catalog/category')
                        ->setStoreId($store->getId())
                        ->setPath($path)
                        ->setName($catName)
                        ->setIsActive(1)
                        ->save();
                    $cache[$namePath] = $cat;
                }
                $catId = $cache[$namePath]->getId();
                $path .= '/'.$catId;
            }
            if ($catId) {
                $catIds[] = $catId;
            }
        }
        return join(',', $catIds);
    }	

    private function _editTierPrices(&$product, $tier_prices_field = false)
    {

        if (($tier_prices_field) && !empty($tier_prices_field)) {

            if(trim($tier_prices_field) == 'REMOVE'){

                $product->setTierPrice(array());

            } else {

                //echo ('adding tier');
                //get current product tier prices
                $existing_tps = $this->_getTierPrices($product);

                $etp_lookup = array();
                //make a lookup array to prevent dup tiers by qty
                foreach($existing_tps as $key => $etp){
                    $etp_lookup[$etp['cust_group'].'-'.intval($etp['price_qty'])] = $key;
                }
                // Mage::log($existing_tps);
                //parse incoming tier prices string
                $incoming_tierps = explode('|',$tier_prices_field);
                $tps_toAdd = array();     
                foreach($incoming_tierps as $tier_str){
                    if (empty($tier_str)) continue;

                    $tmp = array();
                    $tmp = explode('=',$tier_str);

                    if ($tmp[0] == 0 && $tmp[1] == 0) continue;
                    $qty = intval($tmp[0]);
                    $cust_group =  isset($tmp[2])?intval($tmp[2]):32000;
                    $tps_toAdd[$cust_group.'-'.$qty] = array(
                        'website_id' => 0, // !!!! this is hard-coded for now
                        'cust_group' => $cust_group, // !!! so is this
                        'price_qty' => $qty,
                        'price' => $tmp[1],
                        'delete' => ''
                    );

                    //drop any existing tier values by qty
                    if(isset($etp_lookup[$cust_group.'-'.$qty])){
                        unset($existing_tps[$etp_lookup[$cust_group.'-'.$qty]]);
                    }

                }
                //combine array
                $tps_toAdd =  array_merge($existing_tps, $tps_toAdd);
                //save it
                $product->setTierPrice($tps_toAdd);
                //$product->setData('tier_price', $tps_toAdd);
            }

        }

    }
    private function _getTierPrices($product)
    {
        $allGroups = Mage_Customer_Model_Group::CUST_GROUP_ALL;
        $prices = $product->getData('tier_price');
        if (is_null($prices)) {
            $attribute = $product->getResource()->getAttribute('tier_price');
            if ($attribute) {
                $attribute->getBackend()->afterLoad($product);
                $prices = $product->getData('tier_price');
            }
        }

        if (is_null($prices) || !is_array($prices)) {
            return array(array(
                'price'         => $product->getPrice(),
                'website_price' => $product->getPrice(),
                'price_qty'     => 1,
                'cust_group'    => $allGroups,
            ));
        }
        return ($prices) ? $prices : array(); 
    } 
    private function _importAssociationCategory($importData){
        $condition = array();
        $condition[] = array('eq'=>trim($importData['category id']));
        $product = $this->getProductModel()
            ->reset();
        $productId = $product->getIdBySku($importData['sku']);
        if ($productId) {
            $product->load($productId);
        }
        if(count($condition)>0 && $product->getId()){
            $collection = Mage::getModel('catalog/category')->getCollection(); 
            $collection->addFieldToFilter('name',$condition);
            foreach($collection as $category){
                if( $importData['position']>1){
                    $oldProducts = $category->getProductsPosition();
                    $oldProducts[$product->getId()] = $importData['position'];
                    $category->setPostedProducts($oldProducts);
                    $category->save(); 
                }
            } 

        }else{
            $message = Mage::helper('catalog')->__('Skip import row, there are error produc_sku "%s" to id "%s" or category "%s"',$importData['sku'],$product->getId(),$importData['category id']);
            Mage::throwException($message);
        } 
        return true;

    }
    private function _associationCategory($importData){


        $condition = array();
        $cCategoryA = explode(';',$importData['associationCategory']);
        foreach($cCategoryA as $Category){

            // $cname[] = $CategoryA[count($CategoryA)-1]; 
            $condition[] = array('eq'=>$Category);

        }
        if(count($condition)>0){
            $collection = Mage::getModel('catalog/category')->getCollection(); 
            $collection->addFieldToFilter('name',$condition);
            foreach($collection as $category){
                if($category->hasChildren()){
                    $childrens = explode(',',$category->getChildren());
                    $oldProducts = $category->getProductsPosition();
                    foreach($childrens as $children){
                        if( isset($importData['level']) && $importData['level']==2) $this->_subAssociationCategory($children);
                        $subCategory = Mage::getModel('catalog/category')->load($children);
                        if($subCategory->getId()){
                            $subProducts = $subCategory->getResource()->getProductsPosition($subCategory);
                            $products =  array_diff_key($subProducts,$oldProducts);
                            foreach($products as $key=>$value){
                                $oldProducts[$key] = $value;
                            }
                            // Mage::log($subProducts);
                        }
                    }

                    $category->setPostedProducts($oldProducts);
                    //Mage::log($oldProducts);
                    //Mage::log($category->getName().' : '.count($oldProducts));  
                    $category->save(); 
                } 

            }
        } 
        return true;

    }
    private function _subAssociationCategory($id){
        $category = Mage::getModel('catalog/category')->load($id);
        if($category->getId()){
            // get all children
            if (Mage::helper('catalog/category_flat')->isEnabled()) {
                $childrens = (array)$category->getChildrenNodes();
            } else {
                $childrens = $category->getChildren();
            }
            //Mage::log($category->getName().' : '.$childrens); 
            if($childrens){
                $childrens = explode(',',$childrens);
                $oldProducts = $category->getProductsPosition();
                foreach($childrens as $children){
                    $subCategory = Mage::getModel('catalog/category')->load($children);
                    if($subCategory->getId()){
                        $subProducts = $subCategory->getProductsPosition();
                        $products =  array_diff_key($subProducts,$oldProducts);
                        foreach($products as $key=>$value){
                            $oldProducts[$key] = $value;
                        }
                        // Mage::log($subProducts);
                    }
                }
                $category->setPostedProducts($oldProducts);
                //Mage::log($category->getName().' : '.count($oldProducts)); 
                $category->save(); 
            } 


        } 

    }
    private function _categoryOption($importData){
        $condition = array();
        $cCategoryA = explode(';',$importData['CategoryOption']);
        foreach($cCategoryA as $Category){
            // $cname[] = $CategoryA[count($CategoryA)-1]; 
            $condition[] = array('eq'=>trim($Category));

        }
        if(count($condition)>0){

            $addoption = array(
                'is_delete'=>0,
                'title'=>'Get Both T5 T6 Screwdriver',
                'previous_group'=>'',
                'previous_type'=>'',
                'type'=>'drop_down',
                'is_require'=>'0',
                'sort_order'=>'1',
                'values'=>array()
            );
            $addoption['values'][]= array(
                'is_delete'=>0,
                'title'=>'Both T5 T6 ',
                'option_type_id'=>-1,
                'price_type'=>'fixed',
                'price'=>'0.3',
                'sku'=>'42148',
                'sort_order'=>''
            );

            $collection = Mage::getModel('catalog/category')->getCollection(); 
            $collection->addFieldToFilter('name',$condition);
            foreach($collection as $category){
                $productCollection = $category->getProductCollection();
                foreach($productCollection as $product){
                    //$product = Mage::getModel('catalog/product')->load($product->getId());
                    //$opt = Mage::getModel('catalog/product_option');
                    //$opt->addOption($option);
                    // $opt->setProduct($product);
                    //$opt->saveOptions();

                    $hasOptions = false;
                    $options =array();
                    foreach ($product->getProductOptionsCollection() as $option) {
                        if ( strpos($option['title'],'Get Both T5 T6 Screwdriver') !== false ) { 
                            if($hasOptions){
                                $option->getValueInstance()->deleteValue($option->getId());
                                $option->deletePrices($option->getId());
                                $option->deleteTitles($option->getId());
                                $option->delete();
                            }
                            $hasOptions = true;


                        }
                    }
                    if(!$hasOptions){
                        $options[] = $addoption;
                         $product->canAffectOptions(true);
                        $product->setCanSaveCustomOptions(true);
                        $product->setProductOptions($options);
                        $product->save();
                        unset($options); 
                    }elseif(!$product->getHasOptions()){
                        $product->setHasOptions(true);
                        $product->save();
                    }

                }

            }

        }



    }
}
